import { Feature, View } from "ol";
import { defaults } from "ol/control";
import ImageLayer from "ol/layer/Image";
import VectorLayer from "ol/layer/Vector";
import Map from "ol/Map";
import { ImageWMS } from "ol/source";
import VectorSource from "ol/source/Vector";
import conf from "../runtime/configuration";

let mainMap: Map;

export const getMainMap = () => {
    if (mainMap === undefined) {
        mainMap = new Map({
            target: "main-map",
            layers: [],
            view: new View(conf.view),
            controls: defaults({
                zoom: false,
                rotate: false,
                attribution: false
            })
        });
    }
    return mainMap;
}

export function addWMSLayer(layerName: string) {
    let layer = new ImageLayer({
        source: new ImageWMS({
            ratio: 1,
            url: conf.url.geoServer,
            serverType: "geoserver",
            params: {
                "LAYERS": layerName,
                "VERSION": "1.1.1",
            }
        })
    });
    getMainMap().addLayer(layer);
    return layer;
}

export function addVectorLayer(features: Feature<any>[]) {
    let layer = new VectorLayer({
        source: new VectorSource({
            features: features
        })
    });
    getMainMap().addLayer(layer);
    return layer;
}